
var resClass = require('restaurantClass')
var UserData = require('UserData')
var login = require('login')//require('./frontend_services/login')
var coins = require('coins')//require('./frontend_services/coins')
var restaurant = require('restaurants')//require('./frontend_services/restaurants')
var chefTypes = require('chefTypes')//require('./frontend_services/chefTypes')
var users = require('users')
var COMMON_VALUE = require('Common')
var goods = require('goods')
var users = require('users')
var userSkills = require('userSkills')
var CUSTOMER_DATA = require('CustomerData')
var customers = require('customers')
var shareSettings = require('share')
var invitations = require('invitations')
var magicNumber = require('magicNumber')
cc.Class({
    extends: cc.Component,

    properties: {
        text: {
            type: cc.Label,
            default: null
        },
        progressBar: {
            type: cc.Node,
            default: null,
        },
        lastPrecent: {
            type: cc.Integer,
            default: 0,
        }
    },
    sendInviation(wechatData, query) {
        // 更新邀请人列表
        console.log('launch query is ', query)
        query.wechatNickname = wechatData.nickName
        query.wechatAvatarUrl = wechatData.avatarUrl
        if (query && query.openid && query.category === 'customerGettingShare' && UserData.openid !== query.openid) {
            invitations.updateInvitations(query).then((res) => {
                console.log(res)
                console.log('发送邀请拉~!!!')
            })
        }
    },
    downloadUserData() {
        this.users = users
        let self = this
        login((res) => {
            this.UserData.openid = res.data.openid
            let query = null
            try {

                query = wx.getLaunchOptionsSync().query

                wx.getSetting({
                    success(res) {
                        if (!res.authSetting['scope.userInfo']) {
                            wx.authorize({
                                scope: 'scope.userInfo',
                                success() {
                                    wx.getUserInfo({
                                        success: function (res) {
                                            let data = JSON.parse(res.rawData)
                                            users.setUser({
                                                wechatNickname: data.nickName,
                                                gender: data.gender,
                                                city: data.city,
                                                country: data.country,
                                                language: data.language,
                                                province: data.province,
                                                wechatAvatarUrl: data.avatarUrl,
                                            })
                                            UserData.wechatUserInfo = data
                                            self.sendInviation(data, query)
                                        }
                                    })
                                }
                            })
                        } else {
                            wx.getUserInfo({
                                success: function (res) {
                                    let data = JSON.parse(res.rawData)
                                    users.setUser({
                                        wechatNickname: data.nickName,
                                        gender: data.gender,
                                        city: data.city,
                                        country: data.country,
                                        language: data.language,
                                        province: data.province,
                                        wechatAvatarUrl: data.avatarUrl,
                                    })
                                    UserData.wechatUserInfo = data
                                    self.sendInviation(data, query)
                                }
                            })
                        }
                    }
                })
            } catch (err) {
                //cc.log(err)
            }
            try {
                let openDataContext = wx.getOpenDataContext()
                openDataContext.postMessage({
                    openid: res.data.openid
                })
            } catch (err) {
                //cc.log(err)
            }
            let p1 = coins.getCoins()
            let p2 = restaurant.getRestaurant()
            let p3 = chefTypes.getAllChefTypes()
            let p4 = users.getUserInfo()
            let p5 = userSkills.getUserSkill()
            let p6 = shareSettings.getRandomShareSettings()
            let p7 = magicNumber.getMagicNumber()
            Promise.all([p1, p2, p3, p4, p5, p6, p7]).then((result) => {
                //载入顾客的金钱
                this.UserData.setCurrentMoney(result[0].data.coins)
                //console.log("Current Money",this.UserData.getCurrentMoney())
                //载入主厨的元数据
                this.UserData.runtimeState.chefTypeList = result[2].data
                //console.log("chefTypes",result[2])
                for (let j = 0; j < 10; j++) {
                    this.UserData.state.restaurantList.push(null)
                }
                //载入餐厅数据
                let resList = result[1].data
                this.UserData.state.restaurantTotalLevels = 0
                for (let i = 0; i < resList.length; i++) {
                    this.UserData.state.restaurantTotalLevels += resList[i].level
                    let x = resList[i].floor - 1
                    this.UserData.state.restaurantList[x] = new resClass()
                    this.UserData.state.restaurantList[x].resColor = resList[i].resColor
                    this.UserData.state.restaurantList[x].floor = resList[i].floor
                    this.UserData.state.restaurantList[x].Level = resList[i].level
                    this.UserData.state.restaurantList[x].restaurantType = COMMON_VALUE.RESTAURANT_TYPE[resList[i].type]
                    this.UserData.state.restaurantList[x].gainMultiplierList = resList[i].gainMultiplierList ? resList[i].gainMultiplierList : COMMON_VALUE.RESTAURANT_GAIN_MULTIPLY_LIST.matrix[this.floor - 1]
                    if (resList[i].etime) {
                        this.UserData.state.restaurantList[x].etime = resList[i].etime
                    } else {
                        this.UserData.state.restaurantList[x].etime = 0
                    }
                    //cc.log(this.UserData.state.restaurantList[x].etime)
                    //载入主厨
                    let chefID = resList[i].chefID ? resList[i].chefID : null
                    let chefTypeList = UserData.runtimeState.chefTypeList
                    let chefData = null

                    for (let j = 0; j < chefTypeList.length; j++) {
                        if (chefID === chefTypeList[j].basicData.chefID) {
                            chefData = chefTypeList[j]
                            break
                        }
                    }
                    if (chefData) {
                        chefData.chefRadar = resList[i].chefSkills
                    }
                    this.UserData.state.restaurantList[x].chefData = chefData

                    //载入餐厅里的顾客 超时的要删掉远程的数据！
                    for (let m = 0; m < resList[i].customers.length; m++) {
                        for (let n = 0; n < CUSTOMER_DATA.LIST.length; n++) {
                            if (CUSTOMER_DATA.LIST[n].id === resList[i].customers[m].customerID) {
                                if (resList[i].customers[m].etime > CUSTOMER_DATA.LIST[n].duration) {
                                    //删除远程的实例//TOBEFINISHED
                                    customers.deleteCustomerInst(0, resList[i].floor, resList[i].customers[m]._id)
                                } else {
                                    //UserData中写入
                                    let CustomerInst = { custmoerID: resList[i].customers[m].customerID, startTime: resList[i].customers[m].startTime, floor: resList[i].floor }
                                    if (!this.UserData.state.globalCustomerList) {
                                        this.UserData.state.globalCustomerList = []
                                    }
                                    this.UserData.state.globalCustomerList.push(CustomerInst)
                                }
                            }
                        }
                    }
                }
                //getUserInfo

                this.UserData.setReputation(result[3].data.reputations)
                this.UserData.acquiredCustomersList = result[3].data.customers
                this.UserData.acquiredCustomerSharedDetail = result[3].data.invitation_detail

                let coinItemList = result[3].data.goodsByCoins
                let reputationItemList = result[3].data.goodsByReputations
                if(result[3].data.tutorial){//同步教程进度
                    UserData.runtimeState.tutorialProgress = {
                        welcome:            result[3].data.tutorial.welcome?result[3].data.tutorial.welcome:false,
                        chefNode:           result[3].data.tutorial.chefNode?result[3].data.tutorial.chefNode:false,
                        recipeNode:         result[3].data.tutorial.recipeNode?result[3].data.tutorial.recipeNode:false,
                        sellBuildingNode:   result[3].data.tutorial.sellBuildingNode?result[3].data.tutorial.sellBuildingNode:false,
                        sideButton:         result[3].data.tutorial.sideButton?result[3].data.tutorial.sideButton:false,
                    }
                }else{
                    UserData.runtimeState.tutorialProgress = {
                        welcome:false,
                        chefNode:false,
                        recipeNode:false,
                        sellBuildingNode:false,
                        sideButton:false,
                    }
                }
                if (!result[3].data.lastSellBuilding0 && result[3].data.lastSellBuilding0 != 0) {
                    UserData.runtimeState.sellBuildingCoolDown = 0
                } else {
                    this.UserData.runtimeState.sellBuildingCoolDown = 86400 - result[3].data.lastSellBuilding0
                }
                //this.UserData.moneyBuyListOrder
                let order = 0
                this.UserData.state.moneyBuffList = []
                let maxorder = 0
                if (coinItemList.length != 0) {
                    for (let i = 0; i < coinItemList.length; i++) {
                        order = parseInt(coinItemList[i])
                        if (maxorder < order) {
                            maxorder = order
                        }
                    }
                    for (let i = 0; i <= maxorder; i++) {
                        UserData.state.moneyBuffList.push(COMMON_VALUE.MONEY_BUYING_LIST[i])
                    }
                    UserData.state.moneyBuyListOrder = maxorder + 1
                } else {
                    UserData.state.moneyBuyListOrder = 0
                }

                this.UserData.state.reputationBuffList = []
                maxorder = 0
                if (reputationItemList.length != 0) {
                    for (let i = 0; i < reputationItemList.length; i++) {
                        order = parseInt(reputationItemList[i])
                        if (maxorder < order) {
                            maxorder = order
                        }
                    }
                    for (let i = 0; i <= maxorder; i++) {
                        UserData.state.reputationBuffList.push(COMMON_VALUE.REPUTATION_BUYING_LIST[i])
                    }
                    UserData.state.reputationBuyListOrder = maxorder + 1
                } else {
                    UserData.state.reputationBuyListOrder = 0
                }
                //console.log("users",result[3])
                let coolDown = result[4].data
                //UserData.runtimeState.userSkillsCoolDownList.fortunecat
                let timeLeft = 0
                for (let i = 0; i < coolDown.length; i++) {
                    if (coolDown[i].name == "earthshake") {
                        timeLeft = COMMON_VALUE.COOLDOWN_EARTHQUAKE - coolDown[i].etime
                        UserData.runtimeState.userSkillsCoolDownList.earthquake = timeLeft < 0 ? 0 : timeLeft
                    }
                    if (coolDown[i].name == "fortunecat") {
                        timeLeft = COMMON_VALUE.COOLDOWN_FORTUNECAT - coolDown[i].etime
                        UserData.runtimeState.userSkillsCoolDownList.fortunecat = timeLeft < 0 ? 0 : timeLeft
                    }
                    if (coolDown[i].name == "overtime") {
                        timeLeft = COMMON_VALUE.COOLDOWN_OVERTIME - coolDown[i].etime
                        UserData.runtimeState.userSkillsCoolDownList.overtime = timeLeft < 0 ? 0 : timeLeft
                    }
                }

                this.UserData.runtimeState.shareSettings = result[5].data
                
                try {
                    wx.showShareMenu({
                        withShareTicket: true,
                        success: function () {
                            wx.onShareAppMessage(() => {
                                wx.shareAppMessage(result[5].data[0])
                            })
                        }
                    })
                } catch (err) {
                    console.log(err)
                }

                this.UserData.magicNumber = result[6].data.magicNumber
                this.UserData.videoAdInterval = result[6].data.videoAdInterval
                this.UserData.offlineGainRatio = result[6].data.offlineGainRatio

                console.log('Loading Finished', result)
                cc.director.loadScene('Main')
            })/*.catch((error) => {
                console.log('Loading error', error) 
            })*/
        })
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        
        cc.director.preloadScene('Main',
            (now, total) => {
                let precent = now / total
                if (precent < this.lastPrecent) {
                    return
                }
                this.lastPrecent = precent
                this.progressBar.getChildByName('bar').runAction(cc.scaleTo(1, precent, 0.5 + precent * 0.5).easing(cc.easeSineOut()))

                precent *= 100
                precent = precent.toFixed(0)
                this.text.string = precent + '%'
            },
            () => {
                this.UserData = UserData
                this.downloadUserData()
            })
    },
    start() {
        this.time = 0
        this.node.getChildByName('精灵').getComponent('Float').float(null, 1.5 + Math.random(), Math.PI * Math.random())
        this.node.getChildByName('发光生灵').getComponent('Float').float(null, 1, Math.PI * Math.random())
    },
    update(dt) {
        this.time += dt
        let duration = 2
        let minOpacity = 180
        this.progressBar.getChildByName('bar').opacity = minOpacity + Math.sin(this.time * 2 * Math.PI / duration) * (255 - minOpacity)
    },
});
